// 引入SharedArrayBuffer polyfill以解决deprecation警告


const imageConvert = require('./jl_imageconvert_1.0.0-beta1.js');
// import { MessageConstant } from "../base/workTask";
const workTask = require('../base/workTask.js');

class ImageConvertMessage {
    /**
     * 消息-图像转换Jpeg
    */
    static MSG_IMAGE_CONVERT_JPEG = "message_image_convert_jpeg"
    /**
     * 消息-图像转换PNG
    */
    static MSG_IMAGE_CONVERT_PNG = "message_image_convert_png"
    /**
     * 消息-图像转换BMP
    */
    static MSG_IMAGE_CONVERT_BMP = "message_image_convert_bmp"
}
class Key {
    static FUNC = "func"

    /*****************************************输入参数*********************************/

    /**
     * 输入数据()
    */
    static IN_BUFFER = "in_buffer"
    /**
     * 质量百分比
     */
    static QUALITY = "quality";
    /**
     *   对齐字节。默认是0
     */
    static STRIDE = "stride";
    /*****************************************输出结果参数*********************************/

    /**
    * 结果码
    * <p>
    * 说明:<br/>
    * 1. 小于等于0, 视为转码失败，负数为错误码<br/>
    * 2. 大于0，意味着转码成功
    * </p>
    */
    static RESULT = "result"
    /**
     * 输出数据大小
     */
    static OUTPUT_BUFFER_SIZE = "output_buffer_size"
    /**
     * 输出数据
     */
    static OUTPUT_BUFFER = "output_buffer"

}
class Result {
    // 大于0，意味着转码成功
    static RESULT_SUCCESS = 1;
    // 小于等于0, 视为转码失败，负数为错误码
    static RESULT_ERROR = -0xE00;
    static RESULT_ERROR_INVALID_PARAM = -0xE01;
    static RESULT_ERROR_IO_EXCEPTION = -0xE02;
}


var moduleIsInit = false;
function onError(errorCode) {
    const messageObj = new Object();
    messageObj[Key.FUNC] = workTask.MessageConstant.MSG_FINISHED;
    messageObj[Key.RESULT] = errorCode;
    worker.postMessage(messageObj);
}
function onStart() {
    const messageObj = new Object();
    messageObj[Key.FUNC] = workTask.MessageConstant.MSG_START;
    worker.postMessage(messageObj);
}
const inputFileName = "input_file.bin"
const outputFileName = "output_file.bin"

worker.onMessage(function (msg) {
    // processing of workder
    console.log("worker.onMessage image convert", msg);
    if (!moduleIsInit) {
        moduleIsInit = imageConvert.Module.calledRun;        
    }
    const func = msg[Key.FUNC];
    if (func === workTask.MessageConstant.MSG_TERMINATE) {
        //结束当前worker
        //todo 通知 任务已结束了
        // const messageObj = new Object();
        // messageObj[Key.FUNC] = workTask.MessageConstant.MSG_FINISHED;
        // messageObj[Key.RESULT] = Result.RESULT_ERROR;
        // worker.postMessage(messageObj);
        console.log("当前worker 中止结束");
        onError(Result.RESULT_ERROR)
    } else if (func === ImageConvertMessage.MSG_IMAGE_CONVERT_JPEG
        || func === ImageConvertMessage.MSG_IMAGE_CONVERT_PNG
        || func === ImageConvertMessage.MSG_IMAGE_CONVERT_BMP) {

        const module = imageConvert.Module;
        const inBuffer = msg[Key.IN_BUFFER];
        if (inBuffer === undefined) {
            console.log(" inBuffer is undefined");
            onError(Result.RESULT_ERROR_INVALID_PARAM)
            return;
        }

        const tempInBuffer = new Uint8Array(inBuffer);
        // console.log("worker.onMessage 图像转换", tempInBuffer);
        // console.log("worker.onMessage 图像转换", tempInBuffer.length);
        // 将 JavaScript 字符串转换为 C 字符串
       
        let runFunction = function () { }
        const initFunction =function () {
            const inputPtr = module._malloc(module.lengthBytesUTF8(inputFileName) + 1)
            module.stringToUTF8(inputFileName, inputPtr, module.lengthBytesUTF8(inputFileName) + 1);
    
            const outputPtr = module._malloc(module.lengthBytesUTF8(outputFileName) + 1)
            module.stringToUTF8(outputFileName, outputPtr, module.lengthBytesUTF8(outputFileName) + 1);
            return {inputPtr:inputPtr,outputPtr:outputPtr}
        }
        const resultFunction = function (result,ptrObj) {
            let outputData = undefined
            if (result >= Result.RESULT_SUCCESS) {
                outputData = module.FS.readFile(outputFileName, { encoding: 'binary' });
            }
            console.log('Conversion Result:', result);
            console.log('Output Data:', outputData);
            // 通知 任务已结束了
            const messageObj = new Object();
            messageObj[Key.FUNC] = workTask.MessageConstant.MSG_FINISHED;
            messageObj[Key.RESULT] = result;
            messageObj[Key.OUTPUT_BUFFER] = outputData?.buffer;
            // 释放内存（如果需要）
            module._free(ptrObj.inputPtr);
            module._free(ptrObj.outputPtr);
            worker.postMessage(messageObj);
        }
        if (func === ImageConvertMessage.MSG_IMAGE_CONVERT_JPEG) {
            console.log("worker.onMessage 图像转换Jpeg", msg);
            const quality = msg[Key.QUALITY];
            runFunction = function () {
                onStart();
                const ptrObj =initFunction()
                const result = module._image_convert_jpeg(ptrObj.inputPtr, quality,ptrObj.outputPtr)
                resultFunction(result,ptrObj)
            }
        } else if (func === ImageConvertMessage.MSG_IMAGE_CONVERT_PNG) {
            console.log("worker.onMessage 图像转换Png", msg);
            const stride = msg[Key.STRIDE];
            runFunction = function () {
                onStart();
                const ptrObj =initFunction()
                const result = module._image_convert_png(ptrObj.inputPtr, stride, ptrObj.outputPtr)
                resultFunction(result,ptrObj)
            }
        } else if (func === ImageConvertMessage.MSG_IMAGE_CONVERT_BMP) {
            console.log("worker.onMessage 图像转换Bmp", msg);
            runFunction = function () {
                onStart();
                const ptrObj =initFunction()
                const result = module._image_convert_bmp(ptrObj.inputPtr, ptrObj.outputPtr)
                resultFunction(result,ptrObj)
            }
        }

        module.onRuntimeInitialized = function () {
            // 初始化完成
            console.log("module.onRuntimeInitialized", module);
            module.FS.createDataFile('/', inputFileName, tempInBuffer, true, true);
            moduleIsInit = true;
            runFunction()
        }
        if (moduleIsInit) {
            module.FS.createDataFile('/', inputFileName, tempInBuffer, true, true);
            runFunction()
        }
    }
})
